package ren.xxpure.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import ren.xxpure.dao.TokenRepository;
import ren.xxpure.entity.Token;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class SecurityFilter extends OncePerRequestFilter {
	@Resource
	TokenRepository tokenRepository;

	@Override
	protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
		String token = httpServletRequest.getHeader("token");
		if (!StringUtils.hasText(token)) {
			filterChain.doFilter(httpServletRequest, httpServletResponse);
			return;
		}
		String userid;

		JWT jwt = JWTUtil.parseToken(token);
		userid = (String) jwt.getPayload("uid");
		Token tokenUser = tokenRepository.findByUid(userid);
		if (Objects.isNull(tokenUser) || !token.equals(tokenUser.getToken())) {
			throw new RuntimeException("未登录");
		}

		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(tokenUser.getLoginUser(), null, null);
		SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
		filterChain.doFilter(httpServletRequest, httpServletResponse);
	}
}
